<template>
    <div>

        <!-- 弹窗内容 -->
        <div class="flex-1 overflow-hidden flex flex-col md:flex-row">
            <!-- 左侧原文 -->
            <div v-if="props.docItem.docType=='QA'"
                 class="md:w-1/2 p-6 border-r overflow-y-auto h-[550px] mt-0 mb-4 bg-gradient-to-b from-blue-50/30 to-transparent">
                <div>
                    <h3 class="text-lg font-semibold mb-4 text-gray-800 flex items-center gap-2">
                        <i class="fas fa-question-circle text-blue-500"></i>
                        问题
                    </h3>
                    <div class="bg-white rounded-xl p-5 mb-6 shadow-sm border border-blue-100">
                        <p class="text-gray-700 mb-2">{{ props.docItem.content }}</p>
                    </div>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4 text-gray-800 flex items-center gap-2">
                        <i class="fas fa-comment-dots text-blue-500"></i>
                        答案/内容
                    </h3>
                    <div class="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
                        <p class="text-gray-600 whitespace-pre-line">{{ props.docItem.answer }}</p>
                    </div>
                </div>
            </div>
            <div v-else class="md:w-1/2 p-6 border-r overflow-y-auto h-[550px] mt-0 mb-4 bg-gradient-to-b from-blue-50/30 to-transparent">
                <div>
                    <h3 class="text-lg font-semibold mb-4 text-gray-800 flex items-center gap-2">
                        <i class="fas fa-comment-dots text-blue-500"></i>
                        答案/内容
                    </h3>
                    <div class="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
                        <p class="text-gray-600 whitespace-pre-line">{{ props.docItem.content }}</p>
                    </div>
                </div>
            </div>
            <!-- 右侧提问列表和添加区域 -->
            <div class="md:w-1/2 flex flex-col h-[550px] mt-0 mb-4">
                <!-- 添加提问区域 -->
                <div class="p-4 bg-gradient-to-r from-blue-50/50 to-transparent border-b">
                    <div class="flex gap-4">
                        <input
                            v-model="newQuestion"
                            type="text"
                            placeholder="请输入您的提问（最多100字）"
                            maxlength="100"
                            class="flex-1 px-3 py-2 border rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 shadow-sm transition-shadow duration-200 hover:shadow-md"
                        />
                        <button
                            @click="addQuestion"
                            class="!rounded-button whitespace-nowrap px-4 py-2 transition-transform duration-200 flex items-center gap-2"
                            :class="newQuestion.trim() ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white hover:scale-105' : 'bg-gray-100 text-gray-400 cursor-not-allowed'"
                            :disabled="!newQuestion.trim()"
                        >
                            <i class="fas fa-plus"></i>
                            添加
                        </button>
                        <n-popselect @update-value="generateByAi" :options="models" trigger="click">
                            <button
                                class="!rounded-button whitespace-nowrap px-4 py-2 transition-transform duration-200 flex items-center gap-2"
                                :class="'bg-gradient-to-r from-green-500 to-green-600 text-white hover:scale-105' "
                            >
                                <i class="fas " :class="{'fa-robot':!isGenerating, 'fa-spinner fa-spin':isGenerating}"></i>
                                AI生成
                            </button>
                        </n-popselect>

                    </div>
                </div>
                <div class="flex-1 overflow-y-auto p-6">
                    <div v-if="questions && questions.length > 0">
                        <div v-for="(question, idx) in questions" :key="idx"
                             class="mb-4 p-4 bg-white rounded-xl flex justify-between items-start gap-4 shadow-sm border border-gray-100 hover:shadow-md transition-all duration-200 hover:-translate-y-0.5">
                            <div v-if="editingIndex === idx" class="flex-1 flex gap-2">
                                <input
                                    v-model="editingContent"
                                    type="text"
                                    class="flex-1 px-3 py-1.5 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    maxlength="100"
                                />
                                <button
                                    @click="saveEdit(question)"
                                    class="!rounded-button whitespace-nowrap px-2 py-1 bg-gradient-to-r from-blue-500 to-blue-600 text-white hover:scale-105 transition-transform duration-200"
                                >
                                    <i class="fas fa-check text-sm"></i>
                                </button>
                                <button
                                    @click="cancelEdit()"
                                    class="!rounded-button whitespace-nowrap px-2 py-1 bg-gray-100 text-gray-500 hover:bg-gray-200 transition-colors"
                                >
                                    <i class="fas fa-times text-sm"></i>
                                </button>
                            </div>
                            <p v-else class="text-gray-800 flex-1 break-words">{{ question.content }}</p>
                            <div class="flex gap-2" v-if="editingIndex !== idx">
                                <button @click="startEdit(question,idx)"
                                        class="text-gray-400 hover:text-blue-500 transition-colors">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button @click="deleteQuestion(question.id)"
                                        class="text-gray-400 hover:text-red-500 transition-colors">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div v-else class="h-full flex items-center justify-center text-gray-400">
                        <div class="flex flex-col items-center">
                            <i class="fas fa-pencil-alt text-5xl mb-4 text-gray-200"></i>
                            <span>请添加问题</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 确认删除弹窗 -->
        <div v-if="showConfirmDialog"
             class="fixed inset-0 bg-black bg-opacity-30 backdrop-blur-sm z-[60] flex items-center justify-center">
            <div
                class="bg-white rounded-xl p-6 w-[400px] shadow-2xl transform transition-transform duration-300 scale-100 hover:scale-[1.02]">
                <h3 class="text-lg font-medium text-gray-900 mb-4">确认删除</h3>
                <p class="text-gray-600 mb-6">确定要删除这个问题吗？此操作无法撤销。</p>
                <div class="flex justify-end gap-4">
                    <button @click="cancelDelete"
                            class="!rounded-button whitespace-nowrap px-4 py-2 text-gray-600 hover:bg-gray-100 transition-colors duration-200">
                        取消
                    </button>
                    <button @click="confirmDelete"
                            class="!rounded-button whitespace-nowrap px-4 py-2 bg-red-500 text-white hover:bg-red-600 transition-colors duration-200">
                        确认删除
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import {
    onMounted,
    ref,
} from 'vue';
import {JBoltApi} from "@/service/request/index.js";
import {useMessage} from 'naive-ui'

const message = useMessage()
const props = defineProps({
    docId: {
        type: String,
        required: true
    },
    docItem: {
        type: Object,
        required: true
    },

});


const questions = ref([]);
const newQuestion = ref('');
const editingIndex = ref(-1);
const editingContent = ref('');

const showConfirmDialog = ref(false);
const deleteIndex = ref(-1);

//添加问题
const addQuestion = () => {
    if (!newQuestion.value.trim()) {
        message.error('请输入问题');
        return;
    }
    if (newQuestion.value.trim().length > 100) {
        message.error('问题最多100个字');
        return;
    }
    const params = {
        knowledgeBaseId: props.docItem.knowledgeBaseId,
        docType: 'QA',
        content: newQuestion.value,
        fileId: props.docItem.fileId,
        docId: props.docId,
        linkId: props.docItem.docType == 'QA' ? props.docItem.linkId : props.docId,
        linkType: props.docItem.docType == 'QA' ? props.docItem.linkType : 'doc',
        dataType: 'customText',
        docStatus: 100,
    };

    JBoltApi.tryPost('/aiDoc/addQuestionByDocId', params).then((res) => {
        message.success('保存成功');
        newQuestion.value = '';
        getQuestionList();
    }).catch(error => {
        console.error(error)
    })
};
//查询问题
const getQuestionList = () => {
    JBoltApi.tryGet('/aiDoc/getQuestionListByLinkId', {
        docId: props.docId,
    }).then((res) => {
        questions.value = res.data;
    }).catch(error => {
        console.error(error)
    })
}

//删除问题的询问弹窗
const deleteQuestion = (id) => {
    deleteIndex.value = id;
    showConfirmDialog.value = true;
};
//确认删除问题
const confirmDelete = () => {
    JBoltApi.tryGet(`/aiDoc/delete/${deleteIndex.value}`,)
        .then((res) => {
            showConfirmDialog.value = false;
            deleteIndex.value = -1;
            message.success('删除成功');
            getQuestionList();
        }).catch((error) => {
        console.error(error)
    });
};
//取消删除问题
const cancelDelete = () => {
    showConfirmDialog.value = false;
    deleteIndex.value = -1;
};
//开始编辑
const startEdit = (question, idex) => {
    console.log(question)
    editingIndex.value = idex;
    editingContent.value = question.content;
};
//确定编辑
const saveEdit = (question) => {
    if (!editingContent.value.trim()) {
        message.error('请输入问题');
        return;
    }
    question.content = editingContent.value;
    if (questions.value && editingIndex.value > -1) {
        JBoltApi.tryPost('/aiDoc/update', question).then((res) => {
            message.success('保存成功');
            getQuestionList();
            editingIndex.value = -1;
            editingContent.value = '';
        }).catch(error => {
            console.error(error)
        })
    }
};
//取消编辑
const cancelEdit = () => {
    editingIndex.value = -1;
    editingContent.value = '';
};

onMounted(() => {
    getQuestionList();
})


/** ========ai 生成相关 ============== **/
const models = ref([]);
const isGenerating = ref(false);
function loadModels() {
    JBoltApi.tryGet('/aiResource/listAllEnabledType').then((res) => {
        models.value = [{label:'选择一个大模型资源', value:'', disabled: true}, ...res.data.map(item => ({label: item.name,value:item.sn}))]
    }).catch(error => {
        console.error(error)
    })
}
function generateByAi(model) {
    if (isGenerating.value) {
        window.$message.error('正在生成中，请稍后...');
        return;
    }
    isGenerating.value = true
    console.debug(`使用${model}生成问题`);
    JBoltApi.tryPost('aiDoc/generateQuestionByModel', {
        modelSn: model,
        content: props.docItem.docType=='QA'? props.docItem.answer : props.docItem.content,
        doc: {
            knowledgeBaseId: props.docItem.knowledgeBaseId,
            docType: 'QA',
            fileId: props.docItem.fileId,
            docId: props.docId,
            linkId: props.docItem.docType == 'QA' ? props.docItem.linkId : props.docId,
            linkType: props.docItem.docType == 'QA' ? props.docItem.linkType : 'doc',
            dataType: 'customText',
        }
    }, {timeout: 60000}).then(res => {
        console.debug("生成结果：", res.data)
        isGenerating.value =false;
        message.success('生成成功！');
        getQuestionList();
    }).catch(e => {
      isGenerating.value =false;
    })
}
onMounted(() => {
    loadModels()
})

</script>

<style scoped>

</style>